//
//  HealthNewsDetailViewController.m
//  LoveHealth
//
//  Created by 枫哥 on 14-9-18.
//  Copyright (c) 2014年 lanou. All rights reserved.
//

#import "HealthNewsDetailViewController.h"
#import "HealthNewsDetailView.h"
#import "HealthNews.h"
#import "MONActivityIndicatorView.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDB.h"

#import "SQLHelper.h"

#import "UIImageView+WebCache.h"

#import "HealthNewsDetail.h"
#import "SphereMenu.h"

#import "UMSocial.h"
#import "NetHelper.h"
#import "KGStatusBar.h"
@interface HealthNewsDetailViewController ()<MONActivityIndicatorViewDelegate,SphereMenuDelegate,UMSocialUIDelegate>
@property (nonatomic,retain)NSDictionary * dic;
//声明一个loading用于加载未完成时
@property (nonatomic,retain)MONActivityIndicatorView  * indicatorView;
@property (nonatomic,retain)NSString * textStr;
@property (nonatomic,retain)HealthNewsDetail * newsDetail;
@property (nonatomic,retain)NSNumber * newsID;
@property (nonatomic,retain)UIImage * showImage;
@end

@implementation HealthNewsDetailViewController
- (void)dealloc
{
    self.newsID = nil;
    self.showImage = nil;
    self.newsDetail = nil;
    self.textStr = nil;
    self.indicatorView = nil;
    self.newsImageView = nil;
    self.dic = nil;
    self.detailView = nil;
    self.news = nil;
    self.favoriteDetail  = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//重写loadView方法
- (void)loadView
{
//    self.navigationController.navigationBar.translucent = NO;
    //ios7之后scrollView适配问题  设置automaticallyAdjustsScrollViewInsets属性为NO
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.detailView = [[HealthNewsDetailView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = _detailView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"资讯详情";
    self.detailView.detailTitleLabel.text = _news.title;
    //self.detailView.detailImageView.image = _news.showImage;
    
    
    //判断是否是从收藏列表进来的
    if (self.favoriteDetail != nil) {
        
        self.detailView.newsDetail = self.favoriteDetail;
    }else{
        //设置加载loading
        [self setupActivityIndicator];
        
        //判断是从主页列表还是搜索列表进来的
        if (self.searchResult != nil) {
            self.newsID = self.searchResult.ID;
            NSString * url = APIImageURL(self.searchResult.img)
            
            [self.detailView.detailImageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                self.showImage = image;
            }];
            //        [self.detailView.detailImageView setImageWithURL:[NSURL URLWithString:url] success:^(UIImage *image, BOOL cached) {
            //            self.showImage = image;
            //        } failure:nil];
            
        }else{
            self.newsID = self.news.ID;
            self.showImage = self.news.showImage;
        }
        
        NSString * str = [NSString stringWithFormat:@"%@?id=%@",APIHealthNewsDetail,self.newsID];
        
        
        //NSURL * url = [NSURL URLWithString:str];
        _dic = [[NSDictionary alloc] init];
        __block HealthNewsDetailViewController * newsDetailVC = self;
        
        [[NetHelper shareInstance] loadingDataWithUrlString:str urlExpireInSeconds:30 download:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data != nil && connectionError == nil){
            //解析数据
            NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //数据处理
            newsDetailVC.dic = sourceDic[@"yi18"];
            self.textStr = _dic[@"message"];
            _newsDetail = [[HealthNewsDetail alloc]init];
            [_newsDetail setValuesForKeysWithDictionary:newsDetailVC.dic];
            _newsDetail.showImage = self.showImage;
            newsDetailVC.detailView.newsDetail = _newsDetail;
            [_newsDetail release];
                
            }else{
                [KGStatusBar showErrorWithStatus:kNetErrorMessage];
            }
            [newsDetailVC.indicatorView stopAnimating];
            [newsDetailVC setupSphereMenu];

        }];
        
        
        //    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //        //解析数据
        //        NSDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //        //数据处理
        //           newsDetailVC.dic = sourceDic[@"yi18"];
        //        self.textStr = _dic[@"message"];
        //        _newsDetail = [[HealthNewsDetail alloc]init];
        //        [_newsDetail setValuesForKeysWithDictionary:newsDetailVC.dic];
        //        _newsDetail.showImage = self.showImage;
        //        newsDetailVC.detailView.newsDetail = _newsDetail;
        //        [_newsDetail release];
        //        [newsDetailVC.indicatorView stopAnimating];
        //    }];
        
        
        
        
        
        
        //    UIBarButtonItem * collectionBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(didClickCollectionButtonItemAction:)];
        //    self.navigationItem.rightBarButtonItem = collectionBarButtonItem;
        //    [collectionBarButtonItem release];
        
        
        NSLog(@"%@,%@,%@,%@",_news.ID,_news.title,self.textStr,_news.showImage);
        
        
    }
    
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark--------------loading----------------------
//设置loading
- (void)setupActivityIndicator
{
    _indicatorView = [[MONActivityIndicatorView alloc] init];
    _indicatorView.delegate = self; //设置代理
    _indicatorView.numberOfCircles = 6; //圆圈个数
    _indicatorView.radius = 10;//圆圈大小
    _indicatorView.internalSpacing = 3;//圆圈之间的间距
    _indicatorView.center = self.view.center;
    [self.view addSubview:_indicatorView];
    [_indicatorView startAnimating];
}
//指示器 代理方法
- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView circleBackgroundColorAtIndex:(NSUInteger)index
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    CGFloat alpha = 1.0f;
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}


//弹出菜单
- (void)setupSphereMenu
{
    
    UIImage *startImage = [UIImage imageNamed:@"more_img"];
    UIImage *image1 = [UIImage imageNamed:@"favorite_img"];
    UIImage *image2 = [UIImage imageNamed:@"share_img"];
    NSArray *images = @[image1, image2];
    SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:CGPointMake(self.view.bounds.size.width-30, self.view.bounds.size.height-45)
                                                         startImage:startImage
                                                      submenuImages:images];
    sphereMenu.delegate = self;
    [self.view addSubview:sphereMenu];
    
}


- (void)sphereDidSelected:(int)index
{
    NSLog(@"sphere %d selected", index);
    //收藏
    if (index == 0) {
        NSLog(@"sss = %@",_newsDetail);
        NSLog(@"%@",_news.ID);
        SQLHelper * database = [SQLHelper shareInstance];
        BOOL result = [database existWithID:[_news.ID integerValue] tableName:KnewsTableName];
        if (result == NO) {
            [database insertWithValue:_newsDetail tableName:KnewsTableName];
            NSLog(@"收藏成功");
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alert show];
            [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1];
            //[alert release];
        }else{
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alert show];
            [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:0.5];
            //[alert release];
        }

    }
    
    if (index == 1) {
        
        NSString *shareText = [NSString stringWithFormat:@"我在<<爱健康>>看到了一条新闻:%@...........爱生活，爱健康",self.newsDetail.title];             //分享内嵌文字
        UIImage *shareImage = self.newsDetail.showImage;          //分享内嵌图片
        
        //如果得到分享完成回调，需要设置delegate为self
        [UMSocialSnsService presentSnsIconSheetView:self appKey:UmengAppkey shareText:shareText shareImage:shareImage shareToSnsNames:@[UMShareToSina,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToWechatFavorite,UMShareToQzone,UMShareToQQ,UMShareToEmail,UMShareToSms] delegate:self];
        
    }
}

- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
    
}

- (void)dismissAlert:(UIAlertView *)alert
{
    if (alert) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [alert release];
    }
}



#pragma mark---------------------导航栏收藏----------------------------

//- (void)didClickCollectionButtonItemAction:(UIBarButtonItem *)barButton
//{
//    /*
//    //用FMDB将数据存入数据库(documentory目录下  叫favorite)
//
//    NSLog(@"data = %@",NSHomeDirectory());
//    NSString * documentory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString * path = [documentory stringByAppendingPathComponent:@"favorite.sqlite"];
//    //创建数据库
//    FMDatabase * db = [FMDatabase databaseWithPath:path];
//    [db open];
//    if (![db open]) {
//        NSLog(@"Open database failed");
//        return;
//    }
//    //是否有News表 如果没有表
//    if (NO == [self isTableOK:@"News" database:db]){
//        //创建News表
//         [db executeUpdate:@"CREATE TABLE News (id INTEGER PRIMARY KEY NOT NULL UNIQUE, title TEXT NOT NULL, message TEXT, data BLOB)"];
//        //插入数据
//        [self insertDataToDB:db];
//        [db close];
//    }else{
//        //有这个News表
//        FMResultSet * set = [db executeQuery:@"SELECT id FROM News WHERE title = ?",_news.title];
//          if ([set next]){
//              //有表有数据  提示 已经收藏过了
//              UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//              [alert show];
//              [alert release];
//          }else{
//              //有表没这个数据
//              [self insertDataToDB:db];
//              [db close];
//          }
//    }
//   */
//    NSLog(@"sss = %@",_newsDetail);
//    NSLog(@"%@",_news.ID);
//    SQLHelper * database = [SQLHelper shareInstance];
//    BOOL result = [database existWithID:[_news.ID integerValue] tableName:KnewsTableName];
//    if (result == NO) {
//        [database insertWithValue:_newsDetail tableName:KnewsTableName];
//        NSLog(@"收藏成功");
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }else{
//        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//   
//    
//}


/*
- (void)insertDataToDB:(FMDatabase *)db
{
    //插入数据
    NSString * sql = @"insert into News (id,title,message,data) values (?,?,?,?)";
    UIImage * image = _news.showImage;
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    BOOL insert = [db executeUpdate:sql,_news.ID,_news.title,_textStr,data];
    if (insert) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

}
//判断表是否存在的方法
- (BOOL) isTableOK:(NSString *)tableName database:(FMDatabase *)db
{
    FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %ld", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    return NO;
   
}
*/
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
